package cn.tang.tframe.dynconfig.dynlog;

import ch.qos.logback.classic.Level;
import cn.tang.tframe.common.utils.io.PropertiesUtil;
import cn.tang.tframe.dynconfig.DynConfigRegister;
import cn.tang.tframe.dynconfig.IDynConfigProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.Properties;

/**
 * Created by tanghc on 17/2/27.
 */
public class LogLevelMonitor {
	private static Logger logger = LoggerFactory.getLogger(LogLevelMonitor.class);
	private static final String log_groupid="common";
	private static final String log_dataid="loglevel";

	static {
		DynConfigRegister.getInstance().buildOnce(log_groupid, log_dataid, new IDynConfigProcessor() {
			@Override
			public void procesConfig(String config) {
				Properties properties = PropertiesUtil.loadFromString(config);
				changeLogLevel(properties);
			}
		});
	}

	public static void startMonitor(){
		logger.info("init LogLevelMonitor");
	}
	public static void changeLogLevel(Properties properties){
		if(null != properties){

			for(Map.Entry<Object,Object> entry:properties.entrySet()){
				if(null == entry || null == entry.getKey() || null == entry.getValue()){
					logger.info("invalid loglev config: {}",entry);
					continue;
				}
				String key = entry.getKey().toString();
				String value = entry.getValue().toString();
				Level level = Level.toLevel(value);
				if(null == level){
					logger.info("invalid loglev config of level: entry={}",entry);
					continue;
				}
				ch.qos.logback.classic.Logger log = (ch.qos.logback.classic.Logger)LoggerFactory.getLogger(key);
				if(log.getLevel() != null) {
					if(log.getLevel().toInt()  != level.toInt()){
						log.setLevel(level);
					}else{

					}
				}else{
					log.setLevel(level);
				}

			}
		}
	}
}
